package com.cy.dda.service.user.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cy.dda.comm.constant.Constants;
import com.cy.dda.comm.utils.CommonUtils;
import com.cy.dda.dao.mapper.cases.CasesMapper;
import com.cy.dda.dao.mapper.collection.CollectionRecordMapper;
import com.cy.dda.dao.mapper.user.UserMapper;
import com.cy.dda.model.PageBean;
import com.cy.dda.model.Result;
import com.cy.dda.model.domain.user.User;
import com.cy.dda.model.dto.user.UserLoginDTO;
import com.cy.dda.model.enums.CommonStatus;
import com.cy.dda.model.enums.cases.CasesType;
import com.cy.dda.model.enums.collection.RepayType;
import com.cy.dda.model.query.user.DistributableUserListQuery;
import com.cy.dda.model.query.user.UserListAdminQuery;
import com.cy.dda.model.vo.user.DistributableUserListVO;
import com.cy.dda.model.vo.user.UserIndexCasesInfoVO;
import com.cy.dda.model.vo.user.UserIndexCollectionRecordInfoVO;
import com.cy.dda.model.vo.user.UserIndexInfoVO;
import com.cy.dda.model.vo.user.UserListAdminVO;
import com.cy.dda.service.BaseService;
import com.cy.dda.service.user.UserService;

/**
 * 用户 UserService
 *
 * @author: tanyilin
 * @create: 2018年10月31日 下午2:47:58
 */
@Service
public class UserServiceImpl extends BaseService implements UserService {

	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private CasesMapper casesMapper;
	@Autowired
	private CollectionRecordMapper collectionRecordMapper;

	@Override
	public Result login(String mobile, String password) {
		password = CommonUtils.md5Passwod(password);
		UserLoginDTO userLoginDTO = userMapper.login(mobile, password);
		return doLogin(userLoginDTO);
	}
	
	/**
	 * 用户 doLogin
	 * 
	 * @param userLoginDTO
	 * @return
	 */
	private Result doLogin(UserLoginDTO userLoginDTO) {
		if(CommonUtils.isEmpty(userLoginDTO)) {
			return Result.fail("用户手机号码或密码错误");
		}
		CommonStatus status = userLoginDTO.getStatus();
		switch (status) {
			case DISABLE:
				return Result.fail("该账户已被禁用");
				
			case DELETE:
				return Result.fail("不存在该账户");
	
			default:
				break;
		}
		
		// 生成随机token
		String token = UUID.randomUUID().toString();
		String key = Constants.USER_LOGIN_KEY.concat(token);
		userLoginDTO.setToken(token);
		// 把用户登录信息存到redis
		redisTemplate.opsForValue().set(key, userLoginDTO, Constants.LOGIN_TIME, Constants.LOGIN_TIME_UNIT);
		
		return  Result.success("登录成功", userLoginDTO);
	}

	@Override
	@Transactional
	public void addUser(User user) {
		
		User dbUser = new User();
        dbUser.setMobile(user.getMobile());
        dbUser = userMapper.selectOne(dbUser);
        state(dbUser == null, "该手机号码已存在");
		
		Date time = new Date();
		user.setPassword(CommonUtils.md5Passwod(Constants.INIT_PASSWORD));
		user.setStatus(CommonStatus.ENABLE);
		user.setCreateTime(time);
		user.setUpdateTime(time);
		userMapper.insertSelective(user);
	}

	@Override
	@Transactional
	public void resetPassword(String mobile, String newPassword) {
		User dbUser = new User();
        dbUser.setMobile(mobile);
        dbUser = userMapper.selectOne(dbUser);
        state(dbUser != null, "用户不存在");
        String md5NewPassword = CommonUtils.md5Passwod(newPassword);
        User user = new User();
        user.setId(dbUser.getId());
        user.setPassword(md5NewPassword);
        user.setUpdateTime(new Date());
        userMapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public PageBean<UserListAdminVO> selectUserListAdmin(UserListAdminQuery query) {
		int total = userMapper.selectUserListAdminCount(query);
		List<UserListAdminVO> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			list = userMapper.selectUserListAdmin(query);
			list.stream().forEach(u -> {
				u.setStatusText(u.getStatus().getText());
			});
		}
		return new PageBean<UserListAdminVO>(list, total);
	}

	@Override
	@Transactional
	public void updateStatus(Long userId, CommonStatus status) {
		User updateUser = new User();
		updateUser.setId(userId);
		updateUser.setStatus(status);
		updateUser.setUpdateTime(new Date());
		userMapper.updateByPrimaryKeySelective(updateUser);
	}

	@Override
	@Transactional
	public void updatePassword(Long userId, String oldPassword, String newPassword) {
		String md5OldPassword = CommonUtils.md5Passwod(oldPassword);
        String md5NewPassword = CommonUtils.md5Passwod(newPassword);
        User dbUser = new User();
        dbUser.setId(userId);
        dbUser.setPassword(md5OldPassword);
        dbUser = userMapper.selectOne(dbUser);
        state(dbUser != null, "旧密码不正确");
        User user = new User();
        user.setId(userId);
        user.setPassword(md5NewPassword);
        user.setUpdateTime(new Date());
        userMapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public UserIndexInfoVO selectUserIndexInfoVO(Long userId) {
		UserIndexInfoVO userIndexInfoVO = userMapper.selectUserIndexInfoVO(userId);
		return userIndexInfoVO;
	}

	@Override
	public List<UserIndexCasesInfoVO> selectUserIndexCasesInfoVO(Long userId) {
		List<UserIndexCasesInfoVO> list = casesMapper.selectUserIndexCasesInfoVO(userId);
		list.stream().forEach(bean -> {
			if(CasesType.MONTHLY_SUPPLY.equals(bean.getCasesType())) {
				//月供委案，计算动态逾期天数
				bean.setOverdueDays(CommonUtils.getOverdueDays(bean.getOverdueDate()));
			}
		});
		return list;
	}

	@Override
	public List<UserIndexCollectionRecordInfoVO> selectUserIndexCollectionRecordInfoVO(Long userId) {
		List<UserIndexCollectionRecordInfoVO> list = collectionRecordMapper.selectUserIndexCollectionRecordInfoVO(userId);
		list.stream().forEach(c -> {
			if(RepayType.NON_REPAY.equals(c.getRepayType())) {
				c.setTitle(c.getCustomerName().concat(c.getCollectionRecordType().getText()).concat("一次"));
			}else {
				c.setTitle(c.getCustomerName().concat("回款").concat(c.getAmount().toString()).concat("元"));
			}
			c.setCustomerName(null);
			c.setCollectionRecordType(null);
			c.setRepayType(null);
			c.setAmount(null);
		});
		return list;
	}

	@Override
	public PageBean<DistributableUserListVO> selectDistributableUserList(DistributableUserListQuery query) {
		int total = userMapper.selectDistributableUserListCount(query);
		List<DistributableUserListVO> list = new ArrayList<>();
		if(total > 0) {
			query.startPage();
			list = userMapper.selectDistributableUserList(query);
		}
		
		return new PageBean<>(list, total);
	}
	
	
	
	
	
}
